/*
 *  Copyright 2004 Blandware (http://www.blandware.com)
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.blandware.atleap.webapp.action.news;

import com.blandware.atleap.common.Constants;
import com.blandware.atleap.common.NewsModuleConstants;
import com.blandware.atleap.common.util.QueryInfo;
import com.blandware.atleap.model.core.Role;
import com.blandware.atleap.model.core.User;
import com.blandware.atleap.model.news.NewsItem;
import com.blandware.atleap.service.core.UserManager;
import com.blandware.atleap.service.news.NewsManager;
import com.blandware.atleap.webapp.action.core.grid.BaseGridAction;
import com.blandware.atleap.webapp.taglib.core.grid.util.FilterConditions;
import com.blandware.atleap.webapp.taglib.core.grid.util.Grid;
import com.blandware.atleap.webapp.taglib.core.grid.util.SetFilter;
import com.blandware.atleap.webapp.taglib.core.grid.util.StringFilter;
import com.blandware.atleap.webapp.util.core.WebappConstants;
import com.blandware.atleap.webapp.util.core.WebappUtil;
import com.blandware.atleap.webapp.util.news.NewsModuleWebConstants;
import org.apache.struts.Globals;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.Locale;
import java.util.Map;

/**
 * <p>Forward to the page with news archive
 * </p>
 * <p><a href="NewsArchiveAction.java.html"><i>View Source</i></a></p>
 *
 * @author Sergey Zubtsovskiy <a href="mailto:sergey.zubtsovskiy@blandware.com">&lt;sergey.zubtsovskiy@blandware.com&gt;</a>
 * @version $Revision: 1.12 $ $Date: 2006/08/03 10:08:04 $
 * @struts.action path="/news/showArchive"
 * name="newsItemForm"
 * validate="false"
 * @struts.action-forward name="listNewsItems"
 * path=".news.archive"
 */
public final class NewsArchiveAction extends BaseGridAction {
	/**
	 * @param mapping  The ActionMapping used to select this instance
	 * @param form     The optional ActionForm bean for this request (if any)
	 * @param request  The HTTP request we are proceeding
	 * @param response The HTTP response we are creating
	 * @return an ActionForward instance describing where and how
	 *         control should be forwarded, or null if response
	 *         has already been completed
	 */
	public ActionForward execute(ActionMapping mapping, ActionForm form,
	                             HttpServletRequest request, HttpServletResponse response) throws Exception {


		Grid newsGrid = getGridByName(NewsModuleWebConstants.NEWS_ARCHIVE_GRID, request.getSession());
		if ( newsGrid == null ) {
			newsGrid = new Grid(NewsModuleWebConstants.NEWS_ARCHIVE_GRID);
		}

		QueryInfo queryInfo = new QueryInfo();
		StringFilter activeFilter = new StringFilter("item.active");
		activeFilter.createFirstClause(FilterConditions.STRING_EQUAL, "T");
		newsGrid.addFilter(activeFilter);


		SetFilter rolesFilter = new SetFilter("role");
		String userName = request.getRemoteUser();
		UserManager userManager = (UserManager) getBean(Constants.USER_MANAGER_BEAN);
		if ( userName != null ) {
			User user = userManager.retrieveUser(userName);
			List userRoles = user.getRoles();
			if ( userRoles != null ) {
				HashMap selectedElements = new HashMap();
				for ( Iterator i = userRoles.iterator(); i.hasNext(); ) {
					Role role = (Role) i.next();
					selectedElements.put(role.getName(), role.getTitle());
				}
				rolesFilter.setSelectedElements(selectedElements);
				rolesFilter.createFirstClause(FilterConditions.FIELD_IN_SET);
				rolesFilter.createSecondClause(FilterConditions.OBJECT_IS_NULL, FilterConditions.LOGIC_COPULA_OR);
			}
		} else {
			rolesFilter.createFirstClause(FilterConditions.OBJECT_IS_NULL);
		}

		newsGrid.addFilter(rolesFilter);

		queryInfo.setWhereClause(newsGrid.getWhereClause());

		saveGrid(newsGrid, request.getSession());

		Map queryParameters = new HashMap();
		Locale locale = (Locale) request.getSession().getAttribute(Globals.LOCALE_KEY);
		queryParameters.put("localeIdentifier", locale.getLanguage());
		queryInfo.setQueryParameters(queryParameters);

		NewsManager newsManager = (NewsManager) getBean(NewsModuleConstants.NEWS_MANAGER_BEAN);
		List newsItems = newsManager.listNewsItems(queryInfo).asList();

		// set URI
		for ( ListIterator i = newsItems.listIterator(); i.hasNext(); ) {
			NewsItem newsItem = (NewsItem) i.next();
			NewsItem tmp = new NewsItem();
			WebappUtil.copyProperties(tmp, newsItem, request);
			tmp.setUri(WebappUtil.getActionMappingURL(newsItem.getUri(), null, request, WebappConstants.URL_TYPE_CONTEXT_RELATIVE));
			i.set(tmp);
		}

		request.setAttribute(NewsModuleWebConstants.NEWS_ITEMS_COLLECTION_KEY, newsItems);

		// save transaction token in request
		saveToken(request);
		return mapping.findForward("listNewsItems");
	}
}